package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String method = request.getParameter("method");
		if (method == null || method.trim().equals("login")) {
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			boolean rememberMe = request.getParameterValues("rememberMe") != null && request.getParameterValues("rememberMe").length > 0;

			request.getSession().setAttribute("username", username);
			UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
			try {
				SecurityUtils.getSubject().login(token);
			} catch (AuthenticationException e) {
				e.printStackTrace();
			}
			response.sendRedirect("/" + request.getContextPath());
		} else if (method.equals("logout")) {
			SecurityUtils.getSubject().logout();
			request.getSession().removeAttribute("username");
			response.sendRedirect("/" + request.getContextPath());
		}
	}
}
